<template>
  <div id="editor" class="editor">
    <!--页面组件列表展示-->
    <Shape
        v-for="(item, index) in componentData"
        :key="item.id"
        :default-style="item.style"
        :style="getShapeStyle(item.style)"
        :active="item.id === (curComponent || {}).id"
        :element="item"
        :index="index"
        :class="{ lock: item.isLock }"
    >
      <component
          :is="item.component"
          v-if="item.component.startsWith('SVG')"
          :id="'component' + item.id"
          :style="getSVGStyle(item.style)"
          class="component"
          :prop-value="item.propValue"
          :element="item"
          :request="item.request"
      />
      <component
          :is="item.component"
          v-else-if="item.component != 'VText'"
          :id="'component' + item.id"
          class="component"
          :style="getComponentStyle(item.style)"
          :prop-value="item.propValue"
          :element="item"
          :request="item.request"
      />
      <!--   输入框 VText   -->
      <component
          :is="item.component"
          v-else
          :id="'component' + item.id"
          class="component"
          :style="getComponentStyle(item.style)"
          :prop-value="item.propValue"
          :element="item"
          :request="item.request"
          @input="handleInput"
      />
    </Shape>
  </div>

</template>

<script>
import {mapState} from "vuex";
import {getStyle, getComponentRotatedStyle, getShapeStyle, getSVGStyle, getCanvasStyle} from '@/utils/style'
import Shape from './Shape'
import eventBus from "@/utils/eventBus";

export default {
  name: "index",
  components: {Shape},
  data() {
    return {
      svgFilterAttrs: ['width', 'height', 'top', 'left', 'rotate'],
    }
  },

  computed: mapState([
    'componentData', 'curComponent'
  ]),

  methods: {
    getShapeStyle,
    getComponentStyle(style) {
      return getStyle(style, this.svgFilterAttrs)
    },

    getSVGStyle(style) {
      return getSVGStyle(style, this.svgFilterAttrs)
    },

    handleInput(element, value) {
      // 根据文本组件高度调整 shape 高度
      this.$store.commit('setShapeStyle', {height: this.getTextareaHeight(element, value)})
    },

    getTextareaHeight(element, text) {
      let {lineHeight, fontSize, height} = element.style
      if (lineHeight === '') {
        lineHeight = 1.5
      }

      const newHeight = (text.split('<br>').length - 1) * lineHeight * (fontSize || this.canvasStyleData.fontSize)
      return height > newHeight ? height : newHeight
    },

  }
}
</script>

<style lang="scss" scoped>

.editor {
  position: relative;
  background: #fff;
  margin: auto;
  width: 100%;
  height: 100%;

  .component {
    outline: none;
    width: 100%;
    height: 100%;
  }

  .lock {
    opacity: .5;

    &:hover {
      cursor: not-allowed;
    }
  }
}

</style>
